package apis

import (
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	log "github.com/sirupsen/logrus"
	"go-admin/tools/app"
	"io/ioutil"
	"os"
	"path"
	"path/filepath"
	"strconv"
	"strings"
	"time"
)

type UploadFile struct {
	Name    string `json:"name"` // 名称
	Module  string `json:"module"`
	OrderId string `json:"orderId"`
	Url     string `json:"url"` // url
}

func GetZxlibImages(c *gin.Context) {
	module := c.Param("module")
	orderId := c.Param("id")
	var baseUploadsPath = `./uploads/` + module
	if orderId != "-1" {
		baseUploadsPath += `/` + orderId
	}
	log.Info("GetZxlibImages:", baseUploadsPath)
	var files = []UploadFile{}
	if module == "zxlib" {
		files = append(files, getFiles("zxbuild", orderId)...)
		files = append(files, getFiles("zxdesign", orderId)...)
	} else {
		files = append(files, getFiles(module, orderId)...)
	}

	app.OK(c, files, "success")
}

func getFiles(module, orderId string) []UploadFile {
	var files = []UploadFile{}
	var baseUploadsPath = `./uploads/` + module
	if orderId != "-1" {
		baseUploadsPath += `/` + orderId
	}
	filepath.Walk(baseUploadsPath, func(filePath string, info os.FileInfo, err error) error {
		if err == nil && !info.IsDir() {
			fmt.Println(baseUploadsPath, ":", filePath)
			files = append(files, UploadFile{
				Name:    info.Name(),
				Module:  module,
				OrderId: orderId,
				Url:     filePath,
			})
		}
		return nil
	})
	return files
}

func UploadsZxlibImages(c *gin.Context) {
	module := c.Param("module")
	orderId := c.Param("id")
	uploadFile, err := c.FormFile("file")
	if err != nil {
		log.Error("FormFile Error", err)
		app.Err(c, err)
		return
	}
	log.Info("uploadFile:", uploadFile.Size, uploadFile.Filename)
	var baseUploadsPath = `./uploads/` + module + `/` + orderId
	err = os.MkdirAll(baseUploadsPath, 0766)
	if err != nil {
		log.Error("Mkdir Error", err)
		app.Err(c, err)
		return
	}

	newFilePath := baseUploadsPath + `/` + strconv.FormatInt(time.Now().UnixNano()/1e6, 10) + path.Ext(uploadFile.Filename)
	err = c.SaveUploadedFile(uploadFile, newFilePath)
	if err != nil {
		log.Error("Save Error", newFilePath, err)
		app.Err(c, err)
		return
	}
	log.Info("Upload:", newFilePath)
	app.OK(c, nil, newFilePath)
}

func DeleteZxlibImages(c *gin.Context) {
	data, err := ioutil.ReadAll(c.Request.Body)
	if err != nil {
		app.Err(c, err)
		return
	}
	dataMap := make(map[string]string)
	err = json.Unmarshal(data, &dataMap)
	if err != nil {
		app.Err(c, err)
		return
	}
	fileUrl := dataMap["fileUrl"]
	idx := strings.Index(fileUrl, "uploads")
	if idx == -1 {
		app.ErrMsg(c, "fileUrl err:"+fileUrl)
		return
	}
	log.Info("RemoveFile:" + fileUrl)
	err = os.Remove(fileUrl)
	if err != nil {
		log.Error("DeleteZxDesignImages:", err)
		app.Err(c, err)
		return
	}
	app.OK(c, nil, "success")
}
